from django.http import HttpResponse
from django.core.serializers import serialize
from django.utils.timezone import make_aware

from ...models.chat_items import ChatItems
from ...models.chat_history import ChatHistory

from ...utils.data_handle import chatslist_handler, chatsmessage_handler
from ...utils.time_conversion import iso_to_times


from datetime import datetime, timedelta
import json


def chats_list(request):
    '''
    POST
    {
        "title": "你好",
        "created_at": [
            "2024-08-20",
            "2024-08-21"
        ],
        "page": 1,
        "page_size": 15,
        "user_id": 3
    }
    获取所有的对话
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        if "user_id" not in json_obj:
            json_obj['user_id'] = ""

        if json_obj['created_at'] is None:
            json_obj['created_at'] = []

        if len(json_obj['created_at']) == 2:
            start_date = make_aware(datetime.strptime(json_obj['created_at'][0], "%Y-%m-%d"))
            end_date = make_aware(datetime.strptime(json_obj['created_at'][1], "%Y-%m-%d")) + timedelta(days=1)

        if json_obj['user_id'] and json_obj['title'] and len(json_obj['created_at']) > 2:
            all_chatitems_obj = ChatItems.objects.filter(username=json_obj['user_id'], title=json_obj['title'], created_at__gte=start_date, created_at__lte=end_date).order_by('-id')
        elif json_obj['user_id'] and json_obj['title']:
            all_chatitems_obj = ChatItems.objects.filter(username=json_obj['user_id'], title=json_obj['title']).order_by('-id')
        elif json_obj['user_id'] and len(json_obj['created_at']) > 2:
            all_chatitems_obj = ChatItems.objects.filter(username=json_obj['user_id'], created_at__gte=start_date, created_at__lte=end_date).order_by('-id')
        elif json_obj['title'] and len(json_obj['created_at']) > 2:
            all_chatitems_obj = ChatItems.objects.filter(title=json_obj['title'], created_at__gte=start_date, created_at__lte=end_date).order_by('-id')
        elif json_obj['user_id']:
            all_chatitems_obj = ChatItems.objects.filter(username=json_obj['user_id']).order_by('-id')
        elif json_obj['title']:
            all_chatitems_obj = ChatItems.objects.filter(title=json_obj['title']).order_by('-id')
        elif len(json_obj['created_at']) > 2:
            all_chatitems_obj = ChatItems.objects.filter(created_at__gte=start_date, created_at__lte=end_date).order_by('-id')
        else:
            all_chatitems_obj = ChatItems.objects.all().order_by('-id')


        all_chatitems_data = chatslist_handler(all_chatitems_obj, json_obj['page'], json_obj['page_size'])

        res_mes = {
            "code": 0,
            "data": all_chatitems_data
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)
    

def chats_history(request):
    '''
    GET
    History 获取聊天历史记录

    参数
    chat_id=qweasdzxc
    '''

    chatid = request.GET.get('chat_id', None)

    if chatid:
        all_chathistory_obj = ChatHistory.objects.filter(chat_id=chatid)

        json_data_str = serialize('json', all_chathistory_obj)
        json_data = json.loads(json_data_str)

        data = []
        for i in range(len(json_data)):
            json_data[i]['fields']['id'] = json_data[i]['pk']

            # 数据处理
            created_at_second = iso_to_times(json_data[i]['fields']['created_at'])
            updated_at_second = iso_to_times(json_data[i]['fields']['updated_at'])
            json_data[i]['fields']['created_at'] = created_at_second
            json_data[i]['fields']['updated_at'] = updated_at_second

            data.append(json_data[i]['fields'])

        res_mes = {
            "code": 0,
            "data": data
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)
    else:
        res_mes = {
            "code": 1,
            "data": "No history message"
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def chats_remove(request):
    '''
    GET
    RemoveChat 删除对话

    参数
    chat_id=qweasdzxc
    '''
    chatid = request.GET.get('chat_id', None)

    if chatid:
        try:
            # 先删除所有的对话详情记录
            ChatHistory.objects.filter(chat_id=chatid).delete()

            # 再删除对话
            ChatItems.objects.filter(chat_id=chatid).delete()

            res_mes = {
                "code": 0
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        except:
            res_mes = {
                "code": 1,
                "data": "删除数据失败！"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
    else:
        res_mes = {
            "code": 1,
            "data": "请传入 ChatId"
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)
    

def chats_message(request):
    '''
    POST
    Messages 读取聊天记录列表
    {
        "title": "",
        "created_at": [
            "2024-08-20",
            "2024-08-22"
        ],
        "page": 1,
        "page_size": 15,
        "user_id": 10,
        "content": "你好",
        "model": "qwen-plus"
    }
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        search_dict = dict()
        if "user_id" in json_obj and json_obj['user_id']:
            search_dict["username"] = json_obj['user_id']

        if "content" in json_obj and json_obj['content']:
            search_dict["content__icontains"] = json_obj['content']

        if "model" in json_obj and json_obj['model']:
            search_dict["model"] = json_obj['model']

        if json_obj['created_at'] and len(json_obj['created_at']) == 2:
            start_date = make_aware(datetime.strptime(json_obj['created_at'][0], "%Y-%m-%d"))
            end_date = make_aware(datetime.strptime(json_obj['created_at'][1], "%Y-%m-%d")) + timedelta(days=1)

            search_dict["created_at__gte"] = start_date
            search_dict["created_at__lte"] = end_date

        all_chatsmessage = ChatHistory.objects.filter(**search_dict).order_by('-id')

        # all_chatsmessage = ChatHistory.objects.all().order_by('-id')
        all_chatsmessage_data = chatsmessage_handler(all_chatsmessage, json_obj['page'], json_obj['page_size'])

        res_mes = {
            "code": 0,
            "data": all_chatsmessage_data
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def chats_message_remove(request):
    '''
    GET
    RemoveMessage 删除聊天记录

    参数
    id=22
    '''
    removeid = request.GET.get('id', None)

    if removeid:
        try:
            ChatHistory.objects.filter(id=removeid).delete()

            res_mes = {
                "code": 0
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        except:
            res_mes = {
                "code": 1,
                "data": "聊天记录删除数据失败！"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
    else:
        res_mes = {
            "code": 1,
            "data": "请传入 需要删除的id"
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

